package la.iok.aone.monitor.youtube.task;

import la.iok.aone.monitor.youtube.model.YoutubeLink;
import la.iok.aone.monitor.youtube.service.YoutubeLinkService;
import la.iok.aone.monitor.youtube.util.ImportExcel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImportYoutubeExcel implements Runnable {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private YoutubeLinkService youtubeLinkService;
    private File excelFile;

    public ImportYoutubeExcel(YoutubeLinkService youtubeLinkService, File excelFile) {
        this.youtubeLinkService = youtubeLinkService;
        this.excelFile = excelFile;
    }

    @Override
    public void run() {
        List<YoutubeLink> list = importExcel();
        logger.info("Import excel [{}] row num: {}", this.excelFile.getAbsolutePath(), list.size());

        for (YoutubeLink link: list) {
            if (StringUtils.isNotBlank(link.getLink())) {
                link.setParseLink(link.getLink());
                logger.debug("{}", link);
                this.youtubeLinkService.insertOrUpdate(link);
            }
        }
    }

    private List<YoutubeLink> importExcel() {
        try {
            ImportExcel importExcel = new ImportExcel(this.excelFile, 0);
            List<YoutubeLink> list = importExcel.getDataList(YoutubeLink.class);
            return list;
        } catch (InvalidFormatException e) {
            logger.error("", e);
        } catch (IOException e) {
            logger.error("", e);
        } catch (IllegalAccessException e) {
            logger.error("", e);
        } catch (InstantiationException e) {
            logger.error("", e);
        }
        return null;
    }
}
